using System;
using System.Collections;
using Unity.VisualScripting;
using GameFramework.DataTable;
using UnityGameFramework.Runtime;

namespace LS.UGFUnits
{
    [UnitShortTitle("Data Table Row")]
    [UnitSurtitle("Get All")]
    public sealed class GetAllDataTableRow : DataTableUnit
    {
        [Serialize]
        [Inspectable, UnitHeaderInspectable]
        [TypeFilter(typeof(DataRowBase))]
        public System.Type DataTableType { get; set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueOutput DataArray { get; private set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueOutput Count { get; private set; }
        
        protected override void Definition()
        {
            base.Definition();
            DataArray = ValueOutput<DataRowBase[]>(nameof(DataArray));
            Count = ValueOutput<int>(nameof(Count));
        }

        protected override ControlOutput In(Flow flow)
        {
            DataTableBase dataTable = Target?.GetDataTable(DataTableType);
            if (dataTable == null)
            {
                flow.SetValue(DataArray,Array.Empty<DataRowBase>());
                flow.SetValue(Count, 0);
            }
            else
            {
                DataRowBase[] arr = new DataRowBase[dataTable.Count];
                int index = 0;
                foreach (DataRowBase item in (IEnumerable)dataTable)
                {
                    arr[index++] = item;
                }
                flow.SetValue(DataArray, arr);
                flow.SetValue(Count, arr.Length);
            }
            
            return base.In(flow);
        }

    }
}